package logic

import (
	"context"
	"edu-pro/models/cache"
	"edu-pro/models/mysql"
	"errors"

	"edu-pro/edurpc/edurpc"
	"edu-pro/edurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginWithVerificationLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginWithVerificationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginWithVerificationLogic {
	return &UserLoginWithVerificationLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginWithVerificationLogic) UserLoginWithVerification(in *edurpc.UserLoginWithVerificationRequest) (*edurpc.UserLoginWithVerificationResponse, error) {
	//•	手机号 + 验证码登录
	if len(in.Phone) != 11 {
		return nil, errors.New("您输入的手机号码格式不正确，请重新输入")
	}
	var user mysql.User
	mysql.DB.Debug().Where("phone = ?", in.Phone).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("该号码还未注册，请您先注册")
	}
	smsCode, _ := cache.RDB.Get(l.ctx, "sendSms"+in.Phone).Result()
	if smsCode != in.SmsCode {
		return nil, errors.New("验证码已过期")
	}

	return &edurpc.UserLoginWithVerificationResponse{
		UserId: int64(user.ID),
	}, nil
}
